<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="../../lib/element-ui/index.css">
    <link rel="stylesheet" href="./css/index.css">
    <script src="../common/util.js"></script>
    <script src="../../lib/bigscreen/lib/jquery/jquery-1.9.1.min.js"></script>
    <script src="../../lib/bigscreen/js/vue.min.js"></script>
    <script src="../../lib/element-ui/index.js"></script>
    <script src="../../lib/echarts/echarts.min.js"></script>
  
    <script>
        Array.prototype.distinct = function(){
            var arr = this,
                result = [],
                i,
                j,
                len = arr.length;
            for(i = 0; i < len; i++){
                for(j = i + 1; j < len; j++){
                if(arr[i] === arr[j]){
                    j = ++i;
                }
            }
                result.push(arr[i]);
            }
            return result;
        }
    </script>
    <title>历史曲线</title>
</head>
<body>
   <div id="app" v-cloak>
        
    <div class="h-search-wrap">
        <el-form :inline="true" :model="search">
            <el-form-item label="项目">
                <el-select clearable @change="proChange" style="width:120px"  v-model="search.product" placeholder="请选择">
                    <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备">
                <el-select @change="devChange" clearable style="width:130px"  v-model="search.device" placeholder="请选择">
                    <el-option
                    v-for="item in deviceOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备点">
                <el-select   multiple v-model="search.deviceDot" placeholder="请选择">
                        <el-option
                        v-for="item in deviceDotOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="时间段">
                <el-date-picker
                style="width:266px"
                
                v-model="search.timeDistance"
                type="datetimerange"
                range-separator="至"
                value-format="yyyy/MM/dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button @click="getChartData" type="primary">添加</el-button>
            </el-form-item>
            <el-form-item>
                <el-button @click="reset"  type="success">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div id="chart" style="margin-top:37px;height:470px;">
        
    </div>
    <el-row style="margin-top:15px;" type="flex" class="row-bg" justify="center">
        <el-button :disabled="paged==1" @click="prepage" type="primary">上一页</el-button>
        <el-button @click="nextpage" :disabled="paged==totalPage||totalPage==0" type="primary">下一页</el-button>
    </el-row>
   </div>
   <script>
       var nowpage=1;
       function FormatTime (time) {
        var fmt = "yyyy/MM/dd hh:mm:ss";
        var datetime = new Date();
        datetime.setTime(time);
        var o = {
            "M+": datetime.getMonth() + 1, 
            "d+": datetime.getDate(), 
            "h+": datetime.getHours(), 
            "m+": datetime.getMinutes(), 
            "s+": datetime.getSeconds(), 
            "q+": Math.floor((datetime.getMonth() + 3) / 3), 
            "S": datetime.getMilliseconds()
        };
        
       
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (datetime.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        };
    new Vue({
      el: '#app',
      data: function() {
        return {
            on:false,
            paged:1,
            totalPage:0,
            dotData:[],
            productOptions:[],
            deviceDotOptions:[],
            deviceOptions:[],
            search: {
                deviceDot: [],
                timeDistance:'',
                device: '',
                product:''
            } 
        }
      },
      methods:{
        prepage(){
            this.paged--
            this.getChartData()
        },
        nextpage(){
            this.paged++
            this.getChartData()
        },
        reset(){
            location.reload()
        },
        devChange(){
            this.search.deviceDot=[]
            this.getDevDots()
        },
        proChange(){
            this.search.deviceDot=[]
            this.search.device=''
            this.getDevData()
        },
        initChart(ydata,nameArr){
            console.log(ydata,nameArr)
            document.getElementById('chart').removeAttribute('_echarts_instance_');
            var dom = document.getElementById("chart");
            var myChart = echarts.init(dom);
            option = {
                legend: {
                    data: nameArr,
                    right:100
                },
                title: {
                    text: '设备监测运行',
                    lineHeight: 556,
                    left:'90'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        animation: false,
                        type: 'cross'
                    },
                    formatter: function(params) {
                        var result = params[0].name + "<br>";
                        

                        params.forEach(function(item) {
                            result += item.marker + " " + item.seriesName + " : " + FormatTime(item.axisValue) + "</br>";
                        });
                        return result;
                    }
                },
                dataZoom: [
                    {
                        show: true,
                        realtime: true,
                        start: 65,
                        end: 85
                    },
                    {
                        type: 'inside',
                        realtime: true,
                        start: 65,
                        end: 85
                    }
                ],
                xAxis: {
                    type: 'time',
                    boundaryGap: false,
                    axisLabel:{
                        formatter: function (value, index) {
                            return FormatTime(value).replace(' ', '\n');
                        }
                    },
                    splitLine: {
                        show: false
                    }
                   
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}'
                    },
                    scale: true,
                    
                    splitLine: { show: false }
                },
                series:ydata
            }
            myChart.setOption(option, true);
        },
        getDevDots(){
            var that=this
            $.ajax({
                type:'POSt',
                url:baseurl+'/service/page/sensor?paged=1',
                contentType: 'application/json',
                dataType: "json",
                data:JSON.stringify({
                    node_id:that.search.device
                }),
                headers : {'USER-KEY':ucode},
                success: function (e) {
                    if(e.data){
                        that.deviceDotOptions=e.data.data
                    }else{
                        that.deviceDotOptions=[]
                    }
                },
                error: function (e) {
                    
                }
            });
        },
        getDevData(){
            var that=this
            $.ajax({
                type:'POSt',
                url:baseurl+'/service/page/node?paged=1',
                contentType: 'application/json',
                dataType: "json",
                data:JSON.stringify({
                    scene_id:that.search.product
                }),
                headers : {'USER-KEY':ucode},
                success: function (e) {
                    if(e.data){
                        that.deviceOptions=e.data.data
                    }else{
                        that.deviceOptions=[]
                    }
                    
                },
                error: function (e) {
                    
                }
            });
        },
        getProData(){
            var that=this
            $.ajax({
                type:'POST',
                url:baseurl+'/service/page/scene?paged=1&pageSize=1000',
                contentType: 'application/json',
                dataType: "json",
                data:JSON.stringify({}),
                headers : {'USER-KEY':ucode},
                success: function (e) {
                    if(e.data){
                        that.productOptions=e.data.data
                    }else{
                        that.productOptions=[]
                    }
                },
                error: function (e) {
                    
                }
            });
        },
        getChartData(){
            var that=this
            that.dotData=that.dotData.concat(that.search.deviceDot)
            if(that.dotData.distinct().length==0){
                this.$message({
                message: '请选择传感器',
                type: 'warning'
                });
                return
            }
            if(!that.search.timeDistance[0]){
                this.$message({
                message: '请选择时间',
                type: 'warning'
                });
                return
            }
            
            
            
            $.ajax({
                type:'POSt',
                url:baseurl+'/service/sensor/history/data?pageSize=1000&paged='+that.paged,
                contentType: 'application/json',
                dataType: "json",
                data:JSON.stringify({
                    ids:that.dotData.distinct().join(','),
                    start_time: that.search.timeDistance[0]?that.search.timeDistance[0]:'',
                    end_time: that.search.timeDistance[1]?that.search.timeDistance[1]:'',
                }),
                headers : {'USER-KEY':ucode},
                success: function (e) {
                    
                    var alldata=e.data

                    var ydata=[];
                    var nameArr=[]
                    that.totalPage=e.totalPage
    
                    for(var i=0;i<alldata.length;i++){
                        var arr=[]
                        for(let j=0;j<alldata[i].historyDara.length;j++){
                            let inarr=[]
                            inarr.push(alldata[i].historyDara[j].atime)
                            inarr.push(alldata[i].historyDara[j].sdata)
                            arr.push(inarr)
                        }
                        nameArr.push(alldata[i].name)
                        var obj={
                            name:alldata[i].name,
                            type: 'line',
                            smooth:true,
                            data: arr,
                            markPoint: {
                                data: [
                                    {type: 'max', name: '最大值'},
                                    {type: 'min', name: '最小值'}
                                ]
                            },
                            markLine: {
                                data: [
                                    {type: 'average', name: '平均值'}
                                ]
                            }
                        }
                        ydata.push(obj)
                    }
                    console.log(ydata,nameArr)
                    that.initChart(ydata,nameArr)
                },
                error: function (e) {
                    
                }
            });
        }
      },
      created(){
          this.getProData()
      }
    })
  </script> 
</body>
</html>